# -*- coding:utf-8 -*-

__author__ = 'chendaqing'

import re
import urlparse
import functools
import markdown
import string
import hashlib

from datetime import datetime, timedelta
from flask import g, url_for, flash, abort, request, redirect, Markup, current_app
from flaskext.babel import gettext, ngettext
#from flaskext.themes import static_file_url, render_theme_template

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound

from mark.extensions import cached


_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

def slugify(text, delim='-'):
	result = []
	for word in _punct_re.split(text.lower()):
		if word:
			result.append(word)
	return delim.join(result)

markdown = functools.partial(markdown.markdown, safe_mode="remove", output_format="html")

cache = functools.partial(cached.cached, unless = lambda : g.user is not None)

def get_theme():
	return current_app.config['THEME']

"""
def render_template(template, **context):
	return render_theme_template(get_theme(), template, **context)
"""

def request_wants_json():
	# we only accept json if the quality of json is greater than the
	# quality of text/html because text/html is preferred to support
	# browsers that accept on */*
	best = request.accept_mimetypes \
		.best_match(['application/json', 'text/html'])

	return best == 'application/json' and \
		request.accept_mimetypes[best] > request.accept_mimetypes['text/html']


def get_city(ip):
	pass

def shortUrl(origin):
	#加密转成短地址
	chars = list(string.letters + string.digits)
	hex = hashlib.md5(origin).hexdigest()
	#把加密字符的16进制与0x3FFFFFFF进行位与运算
	hexint = 0x3FFFFFFF & int("0x" + hex, 16)
	out_chars = ''
	for j in range(6):
		#把得到的值与0x0000003D进行位与运算，取得字符数组chars索引
		index = 0x0000003D & hexint
		#把取得的字符相加
		out_chars += chars[index]
		hexint = hexint >> 5
	return out_chars

def allowed_file(filename):
	#判断上传的文件类型
	return '.' in filename and \
		filename.rsplit('.', 1)[1] in current_app.config['ALLOWED_EXTENSIONS']


def queryCache(timeout=5 * 60, key = 'view/%s'):
	# 缓存装饰器
	def decorator(f):
		@functools.wraps(f)
		def decorated_func(*args, **kwargs):
			cache_key = key % request.path
			rv = cached.get(cache_key)
			if rv is not None:
				return rv
			rv = f(*args, **kwargs)
			cached.set(cache_key, rv, timeout=timeout)
			return rv
		return decorated_func
	return decorator

if __name__ == '__main__':
	print slugify('USA 中国 世界 没有编辑')
	print shortUrl('http://blog.csdn.net/yanghua_kobe/article/details/7342626')

